package top.yongyan0624.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;
import top.yongyan0624.common.lang.Result;
import top.yongyan0624.entity.*;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author yongyan
 * @since 2021-09-18
 */
@RestController
@RequestMapping("/dynamic")
public class DynamicController extends BaseController {

    @GetMapping("/list")
    public Result list(String title, Long userId) {
        Page<Dynamic> pageData = dynamicService.page(getPage(), new QueryWrapper<Dynamic>()
                .like(StrUtil.isNotBlank(title), "title", title).orderByDesc("create_time"));

        HashMap<String, Long> map = new HashMap<>();
        map.put("user_id", userId);

        pageData.getRecords().forEach(d -> {
            handleDynamicInfo(map, d);
        });

        return Result.success(pageData);
    }

    @GetMapping("/info/{id}")
    public Result info(@PathVariable("id") Long id, Long userId) {
        Dynamic dynamic = dynamicService.getById(id);

        HashMap<String, Long> map = new HashMap<>();
        map.put("user_id", userId);
        handleDynamicInfo(map, dynamic);

        List<DynamicComment> commentList = dynamicCommentService.list(new QueryWrapper<DynamicComment>()
                .eq("dynamic_id", dynamic.getId()));
        commentList.forEach(c -> {
            c.setUser(sysUserService.getById(c.getUserId()));
        });
        dynamic.setCommentList(commentList);

        return Result.success(dynamic);
    }

    private void handleDynamicInfo(HashMap<String, Long> map, Dynamic d) {
        map.put("dynamic_id", d.getId());
        DynamicUser dynamicUser = dynamicUserService.getOne(new QueryWrapper<DynamicUser>().allEq(map));
        if (dynamicUser != null) {
            d.setIsLike(dynamicUser.getLike());
            d.setIsStar(dynamicUser.getStar());
        }

        d.setUser(sysUserService.getById(d.getUserId()));
        d.setImgList(StrUtil.split(d.getImg(), ',', true, true));
    }

    @PostMapping("/save")
    public Result save(@RequestPart Dynamic dynamic, @RequestPart MultipartFile[] imgFiles) {
        try {
            if (imgFiles.length <= 0) {
                return Result.fail("文件为空");
            }
            //文件不为空，处理文件，存储文件并生成随机虚拟路径文件名
            String fileName = handleFile("dynamic", dynamic.getUserId(), imgFiles);

            //设置img虚拟路径
            dynamic.setImg(fileName);

        } catch (IllegalStateException | IOException e) {
            e.printStackTrace();
            return Result.fail("图片上传失败！");
        }

        dynamicService.save(dynamic);

        dynamic.setUser(sysUserService.getById(dynamic.getUserId()));
        dynamic.setImgList(StrUtil.split(dynamic.getImg(), ',', true, true));

        return Result.success(dynamic);
    }

    @PostMapping("/update")
    @PreAuthorize("hasAuthority('dynamic:update')")
    public Result update(@RequestPart Dynamic dynamic, @RequestPart MultipartFile[] imgFiles) {
        try {
            if (imgFiles.length > 0) {
                //文件不为空，处理文件，存储文件并生成随机虚拟路径文件名
                String fileName = handleFile("dynamic", dynamic.getUserId(), imgFiles);

                //设置img虚拟路径
                dynamic.setImg(fileName);
            }
        } catch (IllegalStateException | IOException e) {
            e.printStackTrace();
            return Result.fail("图片上传失败！");
        }

        dynamicService.updateById(dynamic);

        dynamic.setUser(sysUserService.getById(dynamic.getUserId()));
        dynamic.setImgList(StrUtil.split(dynamic.getImg(), ',', true, true));

        return Result.success(dynamic);
    }

    @Transactional
    @PostMapping("/delete")
    @PreAuthorize("hasAuthority('dynamic:delete')")
    public Result delete(@RequestBody Long[] ids) {
        dynamicService.removeByIds(Arrays.asList(ids));
        dynamicUserService.remove(new QueryWrapper<DynamicUser>().in("dynamic_id", ids));
        dynamicCommentService.remove(new QueryWrapper<DynamicComment>().in("dynamic_id", ids));

        return Result.success("");
    }

    @PostMapping("/clickLike")
    public Result clickLike(Long dynamicId, Long userId) {

        HashMap<String, Long> map = new HashMap<>();
        map.put("dynamic_id", dynamicId);
        map.put("user_id", userId);

        Dynamic dynamic = dynamicService.getById(dynamicId);
        DynamicUser dynamicUser = dynamicUserService.getOne(new UpdateWrapper<DynamicUser>().allEq(map));
        if (dynamicUser == null) {
            //更新总数
            dynamic.setLikeNum(dynamic.getLikeNum() + 1);
            dynamicService.updateById(dynamic);

            dynamicUser = new DynamicUser().setDynamicId(dynamicId).setUserId(userId).setLike(true);
            dynamicUserService.save(dynamicUser);
        } else {
            //更新总数
            if (!dynamicUser.getLike()) {
                dynamic.setLikeNum(dynamic.getLikeNum() + 1);
            } else {
                dynamic.setLikeNum(dynamic.getLikeNum() - 1);
            }
            dynamicService.updateById(dynamic);

            //状态取反
            dynamicUser.setLike(!dynamicUser.getLike());
            dynamicUserService.updateById(dynamicUser);
        }

        dynamicUser.setUser(sysUserService.getById(userId));
        dynamicUser.setDynamic(dynamic);

        return Result.success(dynamicUser);
    }

    @PostMapping("/clickStar")
    public Result clickStar(Long dynamicId, Long userId) {

        HashMap<String, Long> map = new HashMap<>();
        map.put("dynamic_id", dynamicId);
        map.put("user_id", userId);

        Dynamic dynamic = dynamicService.getById(dynamicId);
        DynamicUser dynamicUser = dynamicUserService.getOne(new UpdateWrapper<DynamicUser>().allEq(map));
        if (dynamicUser == null) {
            //更新总数
            dynamic.setStarNum(dynamic.getStarNum() + 1);
            dynamicService.updateById(dynamic);

            dynamicUser = new DynamicUser().setDynamicId(dynamicId).setUserId(userId).setStar(true);
            dynamicUserService.save(dynamicUser);
        } else {
            //更新总数
            if (!dynamicUser.getStar()) {
                dynamic.setStarNum(dynamic.getStarNum() + 1);
            } else {
                dynamic.setStarNum(dynamic.getStarNum() - 1);
            }
            dynamicService.updateById(dynamic);

            //状态取反
            dynamicUser.setStar(!dynamicUser.getStar());
            dynamicUserService.updateById(dynamicUser);
        }

        dynamicUser.setUser(sysUserService.getById(userId));
        dynamicUser.setDynamic(dynamic);

        return Result.success(dynamicUser);
    }

    @PostMapping("/sendComment")
    public Result sendComment(@RequestBody DynamicComment comment) {

        dynamicCommentService.save(comment);

        Dynamic dynamic = dynamicService.getById(comment.getDynamicId());
        dynamic.setCommentNum(dynamic.getCommentNum() + 1);
        dynamicService.updateById(dynamic);

        comment.setUser(sysUserService.getById(comment.getUserId()));
        comment.setDynamic(dynamicService.getById(comment.getDynamicId()));

        return Result.success(comment);
    }
}
